import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';

import 'package:openim_common/openim_common.dart';
class PinnedMessagesView extends StatelessWidget {
  const PinnedMessagesView({
    Key? key,
    required this.pinnedMessages,
    this.onTapMessage,
    this.onRemoveMessage,
    this.onToggleVisibility,
    this.isExpanded = false,
    this.currentUserId, // 新增：当前用户ID，用于判断是否显示删除按钮
    this.canRemovePinnedMessage = false, // 新增：是否有移除置顶消息的权限
  }) : super(key: key);

  final List<Message> pinnedMessages;
  final Function(Message)? onTapMessage;
  final Function(Message)? onRemoveMessage;
  final Function()? onToggleVisibility;
  final bool isExpanded;
  final String? currentUserId; // 新增：当前用户ID
  final bool canRemovePinnedMessage; // 新增：是否有移除置顶消息的权限

  @override
  Widget build(BuildContext context) {
    if (pinnedMessages.isEmpty) return const SizedBox.shrink();

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
      decoration: BoxDecoration(
        color: Styles.c_F8F9FA,
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(color: Styles.c_E8EAEF, width: 0.5),
      ),
      child: Column(
        children: [
          // 头部
          GestureDetector(
            onTap: onToggleVisibility,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
              child: Row(
                children: [
                  Icon(
                    Icons.push_pin,
                    size: 16.w,
                    color: Styles.c_0089FF,
                  ),
                  6.horizontalSpace,
                  Text(
                    '置顶消息 (${pinnedMessages.length})',
                    style: TextStyle(
                      color: Styles.c_0089FF,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const Spacer(),
                  Icon(
                    isExpanded ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                    size: 20.w,
                    color: Styles.c_8E9AB0,
                  ),
                ],
              ),
            ),
          ),
          
          // 置顶消息列表
          if (isExpanded) ...[
            Container(
              height: 0.5.h,
              color: Styles.c_E8EAEF,
            ),
            // 将展开语法改为 Column + toList，确保稳定渲染多个置顶项
            Column(
              children: pinnedMessages
                  .map((message) => _buildPinnedMessageItem(message))
                  .toList(),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildPinnedMessageItem(Message message) {

    final canTapToLocate = currentUserId != null && message.sendID == currentUserId;

    return GestureDetector(
      onTap: () => onTapMessage?.call(message),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
        decoration: BoxDecoration(
          // 如果不能点击，显示不同的视觉效果
          color: canTapToLocate ? Colors.transparent : Styles.c_F8F9FA.withOpacity(0.5),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 发送者头像
            AvatarView(
              url: message.senderFaceUrl,
              text: message.senderNickname,
              width: 32.w,
              height: 32.w,
            ),
            8.horizontalSpace,
            
            // 消息内容
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 发送者昵称
                  Text(
                    message.senderNickname ?? '',
                    style: TextStyle(
                      color: Styles.c_6085B1,
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                  2.verticalSpace,
                  
                  // 消息内容
                  Text(
                    _getMessageContent(message),
                    style: TextStyle(
                      color: Styles.c_0C1C33,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w400,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
            
            // 移除按钮 - 只有管理员或群主才能显示
            if (canRemovePinnedMessage)
              GestureDetector(
                onTap: () => onRemoveMessage?.call(message),
                child: Container(
                  padding: EdgeInsets.all(4.w),
                  child: Icon(
                    Icons.close,
                    size: 16.w,
                    color: Styles.c_8E9AB0,
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  String _getMessageContent(Message message) {
    switch (message.contentType) {
      case MessageType.text:
        return message.textElem?.content ?? '';
      case MessageType.picture:
        return '[图片]';
      case MessageType.video:
        return '[视频]';
      case MessageType.voice:
        return '[语音]';
      case MessageType.file:
        return '[文件] ${message.fileElem?.fileName ?? ''}';
      case MessageType.location:
        return '[位置] ${message.locationElem?.description ?? ''}';
      case MessageType.card:
        return '[名片] ${message.cardElem?.nickname ?? ''}';
      // case MessageType.merge:
      //   return '[聊天记录]';
      case MessageType.quote:
        return message.quoteElem?.text ?? '';
      case MessageType.custom:
        final data = IMUtils.parseCustomMessage(message);
        if (data != null) {
          final customType = data['customType'];
          switch (customType) {
            case CustomMessageType.emoji:
              return '[表情]';
            case CustomMessageType.call:
              return '[通话]';
            default:
              return '[自定义消息]';
          }
        }
        return '[自定义消息]';
      default:
        return '[未知消息]';
    }
  }
}
class ChatNoticeView extends StatelessWidget {
  const ChatNoticeView({
    Key? key,
    required this.isISend,
    required this.content,
  }) : super(key: key);
  final bool isISend;
  final String content;

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(maxWidth: maxWidth),
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
      decoration: BoxDecoration(
        color: Styles.c_FFFFFF,
        border: Border.all(color: Styles.c_E8EAEF, width: 1),
        borderRadius: borderRadius(isISend),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              ImageRes.notice.toImage
                ..width = 24.w
                ..height = 24.h,
              StrRes.groupAc.toText..style = Styles.ts_0089FF_17sp,
            ],
          ),
          6.verticalSpace,
          content.toText..style = Styles.ts_0C1C33_17sp,
        ],
      ),
    );
  }
}

class TopNoticeView extends StatelessWidget {
  const TopNoticeView({
    Key? key,
    required this.content,
    this.onPreview,
    this.onClose,
  }) : super(key: key);
  final String content;
  final Function()? onPreview;
  final Function()? onClose;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 10.w, right: 10.w, top: 10.h),
      padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.h),
      decoration: BoxDecoration(
        color: Styles.c_F2F8FF,
        borderRadius: BorderRadius.circular(6.r),
      ),
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: onPreview,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                ImageRes.notice.toImage
                  ..width = 24.w
                  ..height = 24.h,
                2.horizontalSpace,
                StrRes.groupAc.toText..style = Styles.ts_0089FF_17sp,
                const Spacer(),
                ImageRes.closeGroupNotice.toImage
                  ..width = 16.w
                  ..height = 16.h
                  ..onTap = onClose,
              ],
            ),
            8.verticalSpace,
            content.toText
              ..style = Styles.ts_0C1C33_14sp
              ..maxLines = 2
              ..overflow = TextOverflow.ellipsis,
          ],
        ),
      ),
    );
  }
}
